//
//  MineVC.m
//  K-Music
//
//  Created by CHUN on 15/12/27.
//  Copyright © 2015年 CHUN. All rights reserved.
//

#import "MineVC.h"
#import "AppDelegate.h"
#import "YYplayerVC.h"

#import "Friends_see.h"
#import "About_friends.h"
#import "About_Kmusic.h"
#import "Feedback.h"

#import "members_A0.h"


@interface MineVC ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>{
    //退出登录按钮
    UIButton *leaveBtn;
}

@property (nonatomic, strong) UITableView *settingTableView;

@end

@implementation MineVC


-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"其他";
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithIcon:@"play" highIcon:@"play" target:self action:@selector(play_play)];
    
    [self createUI];
    
    

    // Do any additional setup after loading the view from its nib.
}

- (void)play_play
{
    NSLog(@"play");
    //    [MBProgressHUD showErrorWithStatus:@"播放器" toView:self.view];
    
    YYplayerVC* yy = [[YYplayerVC alloc]init];
    
    yy.hidesBottomBarWhenPushed = YES;
    
    yy.musicData= [User_information conversion].musicData[0];
    
    [yy setTracks:[Track remoteTracks]];
    
    [self.navigationController pushViewController:yy animated:NO];
}

- (void)createUI
{
    _settingTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    _settingTableView.delegate = self;
    _settingTableView.dataSource = self;
    _settingTableView.showsVerticalScrollIndicator = NO;
    _settingTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _settingTableView.backgroundColor = RGB(241, 241, 241);
    [self.view addSubview:_settingTableView];
    
    
    UIImageView * HeaderView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 120)];
    HeaderView.image = [UIImage imageNamed:@"Other_pic"];
    _settingTableView.tableHeaderView = HeaderView;
    
    HeaderView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGeture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(ActionDo)];
    [HeaderView addGestureRecognizer:tapGeture];
 
}

#pragma mark ------- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 4){
        return 0;
    }
    return 8.0f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 2) {
        return 3;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    UILabel *iconNameLabel;
    
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        
        iconNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 200, cell.contentView.frame.size.height)];
        iconNameLabel.font = [UIFont systemFontOfSize:15.0f];
        iconNameLabel.textAlignment = NSTextAlignmentLeft;
        [cell.contentView addSubview:iconNameLabel];
        
        UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height-1, WIDTH, 1)];
        lineView2.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:lineView2];
        
        if (indexPath.row != 0) {
            UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
            lineView1.backgroundColor = RGB(241, 241, 241);
            [cell.contentView addSubview:lineView1];
        }
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType  = UITableViewCellAccessoryDisclosureIndicator;
    
    NSArray *iconName1 = @[@"唱星大道",@"我要吐槽",@"清理缓存"];
    
    if (indexPath.section == 0) {
        
        iconNameLabel.text = @"查找好友";
        
    }
    else if (indexPath.section == 1)
    {
        iconNameLabel.text = @"关于会员";
    }
    else if (indexPath.section == 2)
    {
        iconNameLabel.text = iconName1[indexPath.row];
    }
    else if (indexPath.section == 3)
    {
        iconNameLabel.text =@"当前账号";
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",[FileStorage NSUserDefault_getObjectForKey:nickName]];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15.0f];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0 && indexPath.section == 0) {
        
        Friends_see * see = [[Friends_see alloc]init];
        see.navigationItem.title = @"查找好友";
        
        [self.navigationController pushViewController:see  animated:YES];
      
    }
    if (indexPath.row == 0 && indexPath.section == 1) {
         [self.navigationController pushViewController: [About_friends new ]animated:YES];
        
    }
    if (indexPath.row == 0 && indexPath.section == 2) {
         [self.navigationController pushViewController: [About_Kmusic new ]animated:YES];
      
    }
    if (indexPath.row == 1 && indexPath.section == 2) {
         [self.navigationController pushViewController: [Feedback new ]animated:YES];
    }
    if (indexPath.row == 2 && indexPath.section == 2) {
        
        CGFloat CacheSize = [self getCacheSize];
        NSString * cache = [NSString stringWithFormat:@"当前缓存-%.1fM-",CacheSize];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:cache message:@"确定要清理缓存?不清理浏览更流畅耶~" delegate:self cancelButtonTitle:@"立马取消" otherButtonTitles:@"我就要清理", nil];
        alert.tag = 3912;
        [alert show];
    }
    if (indexPath.row == 0 && indexPath.section == 3) {
        [self leaveBtnClick ];
    }
    
}


#pragma mark -------- leaveBtnClick
- (void)leaveBtnClick
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定要退出登录吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag = 3911;
    [alert show];
}

#pragma mark -------- UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3911)
    {
        if (buttonIndex == 1) {
            [self ToLeave];
        }
    }
    
    if (alertView.tag == 3912)
    {
        if (buttonIndex == 1)
        {
            // 清理缓存
            [self myClearCacheAction];

        }
    }

}

- (void)ToLeave
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:access_token];
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:nickName];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:User_id];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:user_phone];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:user_image];
    
    NSString *str = [FileStorage NSUserDefault_getObjectForKey:access_token];
    if ([str isEqual:@""] || str == nil) {
        
        AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        // 在delegate中初始化新的controller
        [delegate initVC];
        
        [self.view removeFromSuperview];
        //        delegate.window.rootViewController = delegate.LoginNavi;
    }

}


- (void)ActionDo
{
    [self.navigationController pushViewController: [members_A0 new ]animated:YES];
//    [MBProgressHUD showErrorWithStatus:@"点击会员用户" toView:self.view];
}


#pragma mark -清理缓存-
// 缓存管理
-(void)myClearCacheAction{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *cachePath = [self getCachePath];
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
        // NSLog(@"files :%lu",(unsigned long)[files count]);
        for (NSString *p in files) {
            NSError *error;
            NSString *path = [cachePath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
        //SDWebImage框架自身清空缓存的实现
        [[SDImageCache  sharedImageCache] cleanDisk];
        
        [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}
//获取缓存大小。。
-(CGFloat)getCacheSize
{
    //获取缓存大小。。
    NSString *cachePath = [self getCachePath];
    CGFloat cacheSize = [self folderSizeAtPath:cachePath];
    return cacheSize;
}
-(void)clearCacheSuccess
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"缓存清理成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}
//计算目录大小-
- (CGFloat)folderSizeAtPath:(NSString *)folderPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) {
        return 0;
    }
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName = nil;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    
    //SDWebImage框架自身计算缓存的实现
    folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    
    return folderSize/(1024.0*1024.0);
}
// 计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
// 获取缓存文件目录
-(NSString*)getCachePath
{
    NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    return cachPath;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
